<template>
  <view class="comments-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left" @tap="back">
        <text class="back-icon">←</text>
      </view>
      <text class="nav-title">评论</text>
      <view class="nav-right"></view>
    </view>

    <!-- 动态预览 -->
    <view class="post-preview" v-if="postData">
      <text class="preview-content">{{ postData.content }}</text>
      <view class="preview-images" v-if="postData.images && postData.images.length > 0">
        <image v-for="(img, index) in postData.images.slice(0, 3)" :key="index" :src="img" class="preview-image"
          mode="aspectFill"></image>
        <view class="more-images" v-if="postData.images.length > 3">+{{ postData.images.length - 3 }}</view>
      </view>
    </view>

    <!-- 评论列表 -->
    <view class="comments-list">
      <view class="comments-header">
        <text class="comments-count">{{ formatNumber(commentsList.length) }}条评论</text>
        <view class="sort-btn" @tap="toggleSort">
          <text>{{ sortByTime ? '最热' : '最新' }}</text>
        </view>
      </view>

      <!-- 评论项 -->
      <view class="comment-item" v-for="(comment, index) in commentsList" :key="comment.id">
        <image :src="comment.avatar" class="comment-avatar" mode="aspectFill"></image>
        <view class="comment-content">
          <view class="comment-header">
            <text class="comment-author">{{ comment.author }}</text>
            <text class="comment-time">{{ comment.time }}</text>
          </view>
          <text class="comment-text">{{ comment.content }}</text>

          <!-- 回复区域 -->
          <view class="replies" v-if="comment.replies && comment.replies.length > 0">
            <view class="reply-item" v-for="(reply, rIndex) in comment.replies" :key="rIndex">
              <text class="reply-author">{{ reply.author }}</text>
              <text class="reply-to" v-if="reply.toAuthor"> 回复 {{ reply.toAuthor }}：</text>
              <text class="reply-content">{{ reply.content }}</text>
            </view>
          </view>

          <!-- 互动按钮 -->
          <view class="comment-actions">
            <view class="action-item" @tap="likeComment(index)">
              <text class="action-icon" :class="{ liked: comment.isLiked }">{{ comment.isLiked ? '❤️' : '🤍' }}</text>
              <text class="action-text">{{ comment.likes > 0 ? comment.likes : '' }}</text>
            </view>
            <view class="action-item" @tap="replyToComment(index)">
              <text class="action-icon">💬</text>
              <text class="action-text">回复</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部评论输入框 -->
    <view class="comment-input-bar">
      <view class="input-container">
        <input type="text" class="comment-input" placeholder="说点什么..." v-model="newComment"
          @focus="showReplyPanel = false" />
      </view>
      <view class="send-btn" @tap="sendComment" :class="{ disabled: !newComment.trim() }">
        <text>发送</text>
      </view>
    </view>

    <!-- 回复输入面板 -->
    <view class="reply-panel" v-if="showReplyPanel">
      <view class="reply-header">
        <text class="reply-to-text">回复 {{ replyToAuthor }}：</text>
        <view class="close-btn" @tap="closeReply">✕</view>
      </view>
      <view class="reply-input-container">
        <input type="text" class="reply-input" placeholder="写下你的回复..." v-model="replyContent" @confirm="sendReply"
          focus />
        <view class="reply-send-btn" @tap="sendReply" :class="{ disabled: !replyContent.trim() }">
          <text>发送</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';

// 获取路由参数
const postId = ref('');
// 动态数据
const postData = ref(null);
// 评论列表
const commentsList = ref([]);
// 排序方式（true：按时间，false：按热度）
const sortByTime = ref(false);
// 新评论内容
const newComment = ref('');
// 回复相关
const showReplyPanel = ref(false);
const replyToAuthor = ref('');
const replyToCommentId = ref('');
const replyContent = ref('');

// 页面加载时
onLoad(options => {
  // 获取路由参数中的postId
  postId.value = options.postId || '';
  console.log('评论页面加载，postId:', postId.value);

  // 加载动态信息
  loadPostInfo();
  // 加载评论列表
  loadComments();
});

// 返回上一页
const back = () => {
  uni.navigateBack();
};

// 加载动态信息
const loadPostInfo = async () => {
  try {
    // 从本地存储获取token
    const storedToken = uni.getStorageSync('token');
    const tokenExpired = uni.getStorageSync('tokenExpired');
    const currentTime = Date.now();
    
    // 检查token是否存在或已过期
    let isTokenExpired = false;
    if (tokenExpired) {
      // 处理可能的时间单位不匹配问题
      if (typeof tokenExpired === 'number' && tokenExpired.toString().length < 13) {
        isTokenExpired = currentTime > (tokenExpired * 1000);
      } else {
        isTokenExpired = currentTime > tokenExpired;
      }
    }
    
    if (!storedToken || storedToken === '' || isTokenExpired) {
      // 没有token或token已过期，使用模拟数据
      console.log('Token不存在或已过期，使用模拟数据');
      
      // 模拟动态数据
      postData.value = {
        id: postId.value,
        content: '请问一下，普通人婚恋有必要签订财产协议吗？以爱之名安全感为由，又如何不打破平等原则不伤感情？',
        images: Array(6).fill('/static/logo.png')
      };
    } else {
      // 调用云函数获取动态信息
      const result = await uniCloud.callFunction({
        name: 'get-post-detail',
        data: {
          postId: postId.value,
          token: storedToken
        }
      });
      
      console.log('获取动态信息结果:', result);
      
      if (result.result && result.result.code === 0 && result.result.data) {
        postData.value = result.result.data;
      } else {
        console.error('获取动态信息失败:', result);
        // 使用默认数据
        postData.value = {
          id: postId.value,
          content: '请问一下，普通人婚恋有必要签订财产协议吗？以爱之名安全感为由，又如何不打破平等原则不伤感情？',
          images: Array(6).fill('/static/logo.png')
        };
      }
    }
  } catch (error) {
    console.error('加载动态信息失败:', error);
    // 使用默认数据
    postData.value = {
      id: postId.value,
      content: '请问一下，普通人婚恋有必要签订财产协议吗？以爱之名安全感为由，又如何不打破平等原则不伤感情？',
      images: Array(6).fill('/static/logo.png')
    };
  }
};

// 加载评论列表
const loadComments = async () => {
  try {
    // 从本地存储获取token
    const storedToken = uni.getStorageSync('token');
    const tokenExpired = uni.getStorageSync('tokenExpired');
    const currentTime = Date.now();
    
    // 检查token是否存在或已过期
    let isTokenExpired = false;
    if (tokenExpired) {
      // 处理可能的时间单位不匹配问题
      if (typeof tokenExpired === 'number' && tokenExpired.toString().length < 13) {
        isTokenExpired = currentTime > (tokenExpired * 1000);
      } else {
        isTokenExpired = currentTime > tokenExpired;
      }
    }
    
    // 显示加载状态
    uni.showLoading({
      title: '加载中...'
    });
    
    if (!storedToken || storedToken === '' || isTokenExpired) {
      // 没有token或token已过期，使用模拟数据
      console.log('Token不存在或已过期，使用模拟数据');
      
      // 模拟评论数据
      commentsList.value = [
        {
          id: '1',
          author: '王二妮',
          avatar: '/static/logo.png',
          content: '我觉得很有必要，提前说清楚总比后来吵架好',
          time: '10分钟前',
          likes: 32,
          isLiked: false,
          replies: [
            {
              id: '1-1',
              author: '匿名用户',
              content: '但是签协议会不会让对方觉得不信任呢？',
              time: '8分钟前'
            },
            {
              id: '1-2',
              author: '王二妮',
              toAuthor: '匿名用户',
              content: '真正的信任是建立在彼此坦诚的基础上的',
              time: '5分钟前'
            }
          ]
        },
        {
          id: '2',
          author: '匿名用户',
          avatar: '/static/logo.png',
          content: '关键还是看两个人的信任程度吧',
          time: '15分钟前',
          likes: 18,
          isLiked: true,
          replies: []
        },
        {
          id: '3',
          author: '法律从业者',
          avatar: '/static/logo.png',
          content: '作为法律从业者，建议有条件的话可以签订，并不是说不相信对方，而是对双方权益的保护',
          time: '20分钟前',
          likes: 45,
          isLiked: false,
          replies: []
        },
        {
          id: '4',
          author: '情感咨询师',
          avatar: '/static/logo.png',
          content: '可以用更温和的方式沟通这个问题，重点是表达对关系的重视而非不信任',
          time: '30分钟前',
          likes: 28,
          isLiked: false,
          replies: []
        }
      ];
    } else {
      // 调用云函数获取评论列表
      const result = await uniCloud.callFunction({
        name: 'get-comments',
        data: {
          postId: postId.value,
          sortByTime: sortByTime.value,
          token: storedToken
        }
      });
      
      console.log('获取评论列表结果:', result);
      
      if (result.result && result.result.code === 0 && result.result.data) {
        commentsList.value = result.result.data || [];
      } else {
        console.error('获取评论列表失败:', result);
        uni.showToast({
          title: result.result.message || '获取评论失败',
          icon: 'none'
        });
        
        // 使用模拟数据作为后备
        commentsList.value = [
          {
            id: '1',
            author: '王二妮',
            avatar: '/static/logo.png',
            content: '我觉得很有必要，提前说清楚总比后来吵架好',
            time: '10分钟前',
            likes: 32,
            isLiked: false,
            replies: [
              {
                id: '1-1',
                author: '匿名用户',
                content: '但是签协议会不会让对方觉得不信任呢？',
                time: '8分钟前'
              },
              {
                id: '1-2',
                author: '王二妮',
                toAuthor: '匿名用户',
                content: '真正的信任是建立在彼此坦诚的基础上的',
                time: '5分钟前'
              }
            ]
          }
        ];
      }
    }
    
    // 排序评论
    sortComments();
  } catch (error) {
    console.error('加载评论失败:', error);
    uni.showToast({
      title: '加载评论失败，请重试',
      icon: 'none'
    });
    
    // 使用模拟数据作为最后后备
    commentsList.value = [
      {
        id: '1',
        author: '王二妮',
        avatar: '/static/logo.png',
        content: '我觉得很有必要，提前说清楚总比后来吵架好',
        time: '10分钟前',
        likes: 32,
        isLiked: false,
        replies: [
          {
            id: '1-1',
            author: '匿名用户',
            content: '但是签协议会不会让对方觉得不信任呢？',
            time: '8分钟前'
          }
        ]
      }
    ];
    sortComments();
  } finally {
    // 隐藏加载状态
    uni.hideLoading();
  }
};

// 切换排序方式
const toggleSort = () => {
  sortByTime.value = !sortByTime.value;
  sortComments();
};

// 排序评论
const sortComments = () => {
  if (sortByTime.value) {
    // 按时间排序（模拟，实际应根据时间戳排序）
    commentsList.value.sort((a, b) => {
      // 这里只是简单模拟，实际应用中应使用时间戳比较
      const timeMap = {
        '刚刚': 0,
        '5分钟前': 1,
        '8分钟前': 2,
        '10分钟前': 3,
        '15分钟前': 4,
        '20分钟前': 5,
        '30分钟前': 6
      };
      return (timeMap[a.time] || 999) - (timeMap[b.time] || 999);
    });
  } else {
    // 按热度排序
    commentsList.value.sort((a, b) => {
      // 先按点赞数，再按回复数
      const aWeight = a.likes + (a.replies ? a.replies.length * 0.5 : 0);
      const bWeight = b.likes + (b.replies ? b.replies.length * 0.5 : 0);
      return bWeight - aWeight;
    });
  }
};

// 点赞评论
const likeComment = async (index) => {
  const comment = commentsList.value[index];
  const isLiked = comment.isLiked;
  
  try {
    // 从本地存储获取token
    const storedToken = uni.getStorageSync('token');
    
    if (!storedToken) {
      console.log('未登录，无法点赞');
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    // 先更新UI，提供即时反馈
    if (isLiked) {
      commentsList.value[index].likes--;
      commentsList.value[index].isLiked = false;
    } else {
      commentsList.value[index].likes++;
      commentsList.value[index].isLiked = true;
    }
    
    // 调用云函数进行点赞/取消点赞
    await uniCloud.callFunction({
      name: 'like-comment',
      data: {
        commentId: comment.id,
        isLiked: !isLiked, // 新的点赞状态
        token: storedToken
      }
    });
    
    console.log('评论点赞操作成功');
    
    // 如果当前是按热度排序，点赞后重新排序
    if (!sortByTime.value) {
      sortComments();
    }
  } catch (error) {
    console.error('评论点赞操作失败:', error);
    
    // 操作失败，回滚UI状态
    if (isLiked) {
      commentsList.value[index].likes++;
      commentsList.value[index].isLiked = true;
    } else {
      commentsList.value[index].likes--;
      commentsList.value[index].isLiked = false;
    }
    
    uni.showToast({
      title: '点赞操作失败，请重试',
      icon: 'none'
    });
  }
};

// 回复评论
const replyToComment = (index) => {
  replyToAuthor.value = commentsList.value[index].author;
  replyToCommentId.value = commentsList.value[index].id;
  replyContent.value = '';
  showReplyPanel.value = true;
};

// 关闭回复面板
const closeReply = () => {
  showReplyPanel.value = false;
  replyContent.value = '';
};

// 发送评论
const sendComment = async () => {
  if (!newComment.value.trim()) return;
  
  // 从本地存储获取token和用户信息
  const storedToken = uni.getStorageSync('token');
  const userInfo = uni.getStorageSync('userInfo') || {};
  
  if (!storedToken) {
    console.log('未登录，无法评论');
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }
  
  // 显示加载状态
  uni.showLoading({
    title: '发送中...'
  });
  
  try {
    // 调用云函数发送评论
    const result = await uniCloud.callFunction({
      name: 'send-comment',
      data: {
        postId: postId.value,
        content: newComment.value.trim(),
        token: storedToken
      }
    });
    
    console.log('发送评论结果:', result);
    
    if (result.result && result.result.code === 0 && result.result.data) {
      // 清空输入框
      newComment.value = '';
      
      // 显示成功提示
      uni.showToast({
        title: '评论发送成功',
        icon: 'success'
      });
      
      // 重新加载评论列表
      loadComments();
    } else {
      console.error('发送评论失败:', result);
      uni.showToast({
        title: result.result.message || '发送评论失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('发送评论异常:', error);
    
    let errorMsg = '网络错误，请稍后重试';
    if (error.errMsg && error.errMsg.includes('timeout')) {
      errorMsg = '请求超时，请检查网络连接';
    } else if (error.errMsg && error.errMsg.includes('auth')) {
      errorMsg = '登录已过期，请重新登录';
    }
    
    uni.showToast({
      title: errorMsg,
      icon: 'none'
    });
  } finally {
    // 隐藏加载状态
    uni.hideLoading();
  }
};

// 发送回复
const sendReply = async () => {
  if (!replyContent.value.trim()) return;
  
  // 从本地存储获取token
  const storedToken = uni.getStorageSync('token');
  
  if (!storedToken) {
    console.log('未登录，无法回复');
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    closeReply();
    return;
  }
  
  // 显示加载状态
  uni.showLoading({
    title: '发送中...'
  });
  
  try {
    // 调用云函数发送回复
    const result = await uniCloud.callFunction({
      name: 'send-reply',
      data: {
        postId: postId.value,
        commentId: replyToCommentId.value,
        content: replyContent.value.trim(),
        toAuthor: replyToAuthor.value,
        token: storedToken
      }
    });
    
    console.log('发送回复结果:', result);
    
    if (result.result && result.result.code === 0 && result.result.data) {
      // 关闭回复面板
      closeReply();
      
      // 显示成功提示
      uni.showToast({
        title: '回复发送成功',
        icon: 'success'
      });
      
      // 重新加载评论列表
      loadComments();
    } else {
      console.error('发送回复失败:', result);
      uni.showToast({
        title: result.result.message || '发送回复失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('发送回复异常:', error);
    
    let errorMsg = '网络错误，请稍后重试';
    if (error.errMsg && error.errMsg.includes('timeout')) {
      errorMsg = '请求超时，请检查网络连接';
    } else if (error.errMsg && error.errMsg.includes('auth')) {
      errorMsg = '登录已过期，请重新登录';
    }
    
    uni.showToast({
      title: errorMsg,
      icon: 'none'
    });
  } finally {
    // 隐藏加载状态
    uni.hideLoading();
  }
};

// 格式化数字
const formatNumber = (num) => {
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k';
  }
  return num;
};
</script>

<style scoped>
.comments-container {
  min-height: 100vh;
  background-color: #f7f7f7;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100rpx;
  background-color: white;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-left {
  width: 40rpx;
}

.back-icon {
  font-size: 40rpx;
  color: #333;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-right {
  width: 40rpx;
}

/* 动态预览 */
.post-preview {
  background-color: white;
  padding: 20rpx 30rpx;
  border-bottom: 10rpx solid #f7f7f7;
}

.preview-content {
  font-size: 28rpx;
  color: #333;
  line-height: 44rpx;
  display: block;
  margin-bottom: 20rpx;
}

.preview-images {
  display: flex;
  gap: 10rpx;
  position: relative;
}

.preview-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  background-color: #f5f5f5;
}

.more-images {
  position: absolute;
  top: 0;
  left: 250rpx;
  width: 120rpx;
  height: 120rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 8rpx;
  font-size: 28rpx;
}

/* 评论列表 */
.comments-list {
  background-color: white;
  padding-bottom: 30rpx;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.comments-count {
  font-size: 28rpx;
  color: #333;
}

.sort-btn {
  padding: 6rpx 20rpx;
  background-color: #f5f5f5;
  border-radius: 20rpx;
}

.sort-btn text {
  font-size: 26rpx;
  color: #666;
}

/* 评论项 */
.comment-item {
  display: flex;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.comment-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  background-color: #f5f5f5;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.comment-author {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.comment-time {
  font-size: 24rpx;
  color: #999;
}

.comment-text {
  font-size: 28rpx;
  color: #333;
  line-height: 44rpx;
  display: block;
  margin-bottom: 15rpx;
  word-break: break-all;
}

/* 回复区域 */
.replies {
  background-color: #f9f9f9;
  padding: 15rpx;
  border-radius: 10rpx;
  margin-bottom: 15rpx;
}

.reply-item {
  margin-bottom: 10rpx;
  font-size: 26rpx;
  line-height: 40rpx;
}

.reply-item:last-child {
  margin-bottom: 0;
}

.reply-author {
  color: #6d4aff;
  font-weight: bold;
}

.reply-to {
  color: #999;
}

.reply-content {
  color: #333;
}

/* 互动按钮 */
.comment-actions {
  display: flex;
  gap: 40rpx;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.action-icon {
  font-size: 28rpx;
  color: #999;
}

.action-icon.liked {
  color: #ff4d4f;
}

.action-text {
  font-size: 24rpx;
  color: #999;
}

/* 底部评论输入框 */
.comment-input-bar {
  display: flex;
  align-items: center;
  padding: 15rpx 30rpx;
  background-color: white;
  border-top: 1rpx solid #f0f0f0;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 99;
}

.input-container {
  flex: 1;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  padding: 0 30rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
}

.comment-input {
  width: 100%;
  height: 100%;
  font-size: 28rpx;
  color: #333;
  background-color: transparent;
}

.send-btn {
  margin-left: 20rpx;
  padding: 10rpx 30rpx;
  background-color: #6d4aff;
  border-radius: 40rpx;
  color: white;
  font-size: 28rpx;
}

.send-btn.disabled {
  background-color: #c8bfff;
  color: #e6e1ff;
}

/* 回复输入面板 */
.reply-panel {
  position: fixed;
  bottom: 110rpx;
  left: 0;
  right: 0;
  background-color: white;
  border-top: 1rpx solid #f0f0f0;
  border-bottom: 1rpx solid #f0f0f0;
  z-index: 98;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.reply-to-text {
  font-size: 28rpx;
  color: #333;
}

.close-btn {
  font-size: 36rpx;
  color: #999;
}

.reply-input-container {
  display: flex;
  align-items: center;
  padding: 15rpx 30rpx;
}

.reply-input {
  flex: 1;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  padding: 0 30rpx;
  height: 80rpx;
  font-size: 28rpx;
  color: #333;
}

.reply-send-btn {
  margin-left: 20rpx;
  padding: 10rpx 30rpx;
  background-color: #6d4aff;
  border-radius: 40rpx;
  color: white;
  font-size: 28rpx;
}

.reply-send-btn.disabled {
  background-color: #c8bfff;
  color: #e6e1ff;
}
</style>